<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>

			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-cell icon="calendar" size="large">
											<view slot="title" class="u-slot-title">
												<text class="u-cell-text u-cell_text">申请人填写</text>
											</view>
										</u-cell>
									</u-col>
								</u-row>


								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="模具:" @click="openBaseScreen('模具')"
											required>
											<u--input v-model="baseFormData.MoludName" placeholder="请选择模具" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申请人:">
											<u--input v-model="baseFormData.ApplyForMan" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申请时间:">
											<u--input v-model="baseFormData.ApplyForTime" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="8">
										<u-form-item labelWidth="auto" label="故障描述:" required>
											<u--input v-model="baseFormData.BXContent" placeholder="请输入故障描述"
												:readonly="disableShow == 2||disableShow == 3" border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-cell icon="calendar" size="large">
											<view slot="title" class="u-slot-title">
												<text class="u-cell-text u-cell_text">维修人填写</text>
											</view>
										</u-cell>
									</u-col>
								</u-row>


								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修编号:" required>
											<u--input v-model="baseFormData.BillNO" placeholder="自动带出维修编号" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修人:" required
											@click="openBaseScreen('人员')" required>
											<u--input v-model="baseFormData.MaintainMan" placeholder="请选择维修人" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修内容:" required>
											<u--input v-model="baseFormData.GZCause" placeholder="请输入维修内容"
												:readonly="disableShow == 1||disableShow == 3" border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修方式:" required @click="addWay('WXFS')">
											<u--input v-model="baseFormData.WayName" placeholder="请选择维修方式" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修费用:" required>
											<u--input v-model="baseFormData.Cost" placeholder="请输入维修费用" type="number"
												:readonly="disableShow == 1||disableShow == 3" border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修状态:" required>
											<u--input v-model="baseFormData.WCStatus?'已维修':'未维修'" placeholder="维修状态"
												readonly border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修结果:" required @click="addWay('SBWX')">
											<u--input v-model="baseFormData.FResultName" placeholder="请选择维修结果" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修开始时间:">
											<u--input v-model="baseFormData.BeginTime" placeholder="自动带出开始时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修结束时间:" required>
											<u--input v-model="baseFormData.WCTime" placeholder="自动带出结束时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
							</u--form>

						</view>
					</view>
					<view class="DetailsbottomBtns"  v-show="buttonShow">
						<button block @click="submit" class="button1">
							{{buttonTitle}}
						</button>
					</view>

				</view>
			</template>
		</st-mc-framework>

		<u-action-sheet :actions="StateList" :show="StateShow" @select="StateClick"
			@close="StateShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>


		<u-modal :show="modalshow" :title="modaltitle" width="400px" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				baseFormData: {
					FaultDocID: 0,
					EquipmentName: '',
					ApplyForMan: '',
					ApplyForTime: '',
					BXContent: '',
					BillNO: '',
					MaintainMan: '',
					GZCause: '',
					Way: '',
					WayName: '',
					Cost: '',
					WCStatus: '',
					FResult: 0,
					FResultName: '',
					BeginTime: '',
					WCTime: '',
					BillDate: '',
					MoludID: '',
					MoludName: ''
				},
				buttonShow: true,
				buttonTitle: '保存',
				disableShow: 1,
				StateShow: false,
				StateList: [],
				moduleShow: false,
				moduleList: [],

				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName;
			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
			that.ChangedisableShow()
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (onLoad.MaintainMouldID) {
				setLoading(true);
				that.queryList('列表', onLoad.MaintainMouldID)
				return;
			}
			if (onLoad.Detailsitem) {
				setLoading(true);
				const dispatchItem = JSON.parse(onLoad.Detailsitem);
				if (dispatchItem.MaintainMouldID) {
					setLoading(true);
					that.queryList('列表', dispatchItem.MaintainMouldID)
					return;
				}
				const formDefaults = {
					...dispatchItem,
					MoludName: dispatchItem.MoludName ? dispatchItem.MoludName : dispatchItem.MoludCode,
					BXContent: dispatchItem.GZContent
				}
				console.log(formDefaults);
				this.baseFormData = Object.assign(this.baseFormData, formDefaults);
			}
			// 统一处理表单默认值
			const formDefaults = {
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
				ApplyForMan: UserInfo.EmplName,
				CheckupID: UserInfo.EmplID,
				BillDate: getFormatDateTime(new Date()),
				ApplyForTime: getFormatDateTime(new Date())
			};

			this.assignFormData(this.baseFormData, formDefaults);
			setLoading(false);
		},
		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				console.log(res.data);
				this.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		methods: {
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},

			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {


				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			ChangedisableShow() {
				var that = this
				if (that.buttonTitle == '保存') {
					that.disableShow = 1
				} else {
					that.disableShow = 2
				}
			},

			addPeriodTypeClick() {
				var that = this
				that.disableShow = 2
				if (!that.baseFormData.BeginTime) {
					that.buttonTitle = '开始维修'
				} else if (that.baseFormData.BeginTime) {
					that.buttonTitle = '结束维修'
				}
				if (that.baseFormData.MaintainMouldID && that.baseFormData.BeginTime && that.baseFormData
					.WCTime) {
					that.buttonShow = false
					that.disableShow = 3
				}
				that.$forceUpdate()
			},

			StateClick(e) {
				var that = this;
				var formDefaults = {}


				if (that.StateName == 'SBWX') {
					formDefaults = {
						FResult: e.id,
						FResultName: e.name,
					};
				} else {
					formDefaults = {
						Way: e.id,
						WayName: e.name,
					};
				}
				that.assignFormData(that.baseFormData, formDefaults)
			},
			addWay(str) {
				var that = this;
				if (that.disableShow == 2 && that.buttonShow == true) {
					that.StateName = str
					console.log(str);
					that.Request.request('getViewState', {
						FType: str
					}, function(ret) {
						console.log(ret.data.ds);
						if (ret.status == 200) {
							that.StateList = ret.data.ds
						}
					})
					this.StateShow = true
				}

			},


			getValue(payload) {

				var that = this;
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'人员': () => ({
						MaintainMan: data.UserName,
					}),
					'模具': () => ({
						MoludID: data.MoludID,
						MoludName: data.MoludCode
					})
				};
				if (typeHandlers[type]) {
					Object.assign(this.baseFormData, typeHandlers[type]());
				}
			},
			openBaseScreen(str) {
				var that = this;
				var obj;
				var show = false
				if (str == '人员') {
					if (that.disableShow == 2 && that.buttonShow == true) {
						show = true
					}

					obj = {
						cmd: 'getEmplByJobName',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'UserName', //查询结果显示的字段
						},
						param: {
							JobName: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				} else if (str == '模具') {
					console.log(that.disableShow, that.buttonShow);
					if (that.disableShow == 1 && that.buttonShow == true) {
						show = true
					}
					console.log(show);
					obj = {
						cmd: 'ZS_Droplist_Molud',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'MoludCode', //查询结果显示的字段
						},
						param: {
							MoludID: 0,
							FWorkshopID: that.FWorkshopID,
							MoludCode: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				}

				if (show == true) {
					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}



			},



			submit() {
				var that = this
				var show = true
				var msg

				if (that.baseFormData.BXContent == '' || that.baseFormData.BXContent == null) {
					msg = '请输入故障描述'
					show = false
				}
				if (that.baseFormData.MoludName == '' || that.baseFormData.MoludName == null) {
					msg = '请选择模具'
					show = false
				}
				if (that.buttonTitle == '开始维修') {

					if (that.baseFormData.MaintainMan == '' || that.baseFormData.MaintainMan == null) {
						msg = '请选择人员'
						show = false
					} else if (that.baseFormData.GZCause == '' || that.baseFormData.GZCause == null) {
						msg = '请输入维修内容'
						show = false
					} else if (that.baseFormData.WayName == '' || that.baseFormData.WayName == null) {
						msg = '请选择维修方式'
						show = false
					}
				} else if (that.buttonTitle == '结束维修') {
					if (that.baseFormData.FResultName == '' || that.baseFormData.FResultName == null) {
						msg = '请选择维修结果'
						show = false
					}
				}
				if (show) {
					if (that.buttonTitle == '开始维修') {
						const formDefaults = {
							Cost: that.baseFormData.Cost ? that.baseFormData.Cost : 0,
						}
						that.assignFormData(that.baseFormData, formDefaults)
					}

					var obj = {
						MaintainMouldID: that.baseFormData.MaintainMouldID ? that.baseFormData
							.MaintainMouldID : 0,
						ApplyForMan: that.baseFormData.ApplyForMan,
						MoludID: that.baseFormData.MoludID,
						ApplyForTime: that.baseFormData.ApplyForTime,
						BXContent: that.baseFormData.BXContent,
						BillNO: that.baseFormData.BillNO,
						MaintainMan: that.baseFormData.MaintainMan,
						GZCause: that.baseFormData.GZCause,
						Way: that.baseFormData.Way,
						Cost: that.baseFormData.Cost != null ? that.baseFormData.Cost : '',
						WCStatus: that.baseFormData.WCStatus,
						FResult: that.baseFormData.FResult ? that.baseFormData.FResult : '',
						BeginTime: that.baseFormData.BeginTime,
						WCTime: that.baseFormData.WCTime,
						BillDate: that.baseFormData.BillDate,
						FType: 'MJWX',
						FaultDocID: that.baseFormData.FaultDocID,
					}

					console.log(obj);
					that.Request.request('saveMaintainMould', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							that.queryList('刷新', ret.data.ds[0].MaintainMouldID)
						}
					})
				} else {
					that.showModal('报错', msg);


				}
			},
			queryList(str, id) {
				var that = this
				try {
					var obj = {
						PageIndex: 1,
						PageSize: 30,
						FBDate: getBefore7DateTime(),
						FEDate: getFormatDateTime(new Date()),
						WCStatus: -1,
						MaintainMouldID: id
					}
					that.Request.request('getMaintainMouldListD', obj, (ret) => {
						console.log(ret.data);
						that.showMLoading = false
						const [firstItem] = ret.data.ds;
						const formDefaults = {
							...firstItem,
							ApplyForTime: firstItem.ApplyForTime ? firstItem.ApplyForTime.split('T')[0] : '',
							WCTime: formatDateTime(firstItem.WCTime),
							BeginTime: formatDateTime(firstItem.BeginTime),
						};
						if (str == '列表') {
							formDefaults.MaintainMan = that.baseFormData.MaintainMan ? that.baseFormData
								.MaintainMan : that.$store.state.UserInfo.EmplName
						}
						console.log(firstItem);
						that.assignFormData(that.baseFormData, formDefaults)
						that.addPeriodTypeClick()

					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},


			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	.u_form .u-cell__body {
		padding: 5px 0 !important;

		.u-cell_text {
			font-weight: 600 !important;
		}
	}
</style>